<template>
  <div class="admin-title-application">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>职称评审管理</span>
          <el-button type="primary" size="small" @click="fetchApplications">刷新</el-button>
        </div>
      </template>
      <el-table :data="applications" style="width: 100%">
        <el-table-column prop="teacherName" label="教师姓名" width="120" />
        <el-table-column prop="teacherNumber" label="工号" width="120" />
        <el-table-column prop="applyTitle" label="申请职称" width="120" />
        <el-table-column prop="department" label="院系" width="120" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="材料" width="120">
          <template #default="scope">
            <a v-if="scope.row.attachment" :href="getAttachmentUrl(scope.row.attachment)" target="_blank">下载附件</a>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button v-if="scope.row.status === '审批中'" type="success" size="small" @click="approve(scope.row.id)">同意</el-button>
            <el-button v-if="scope.row.status === '审批中'" type="danger" size="small" @click="showRejectDialog(scope.row.id)">不同意</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="rejectDialogVisible" title="拒绝职称申请" width="400px">
        <el-form :model="rejectForm">
          <el-form-item label="原因" label-width="60px">
            <el-input v-model="rejectForm.reason" type="textarea" :rows="3" placeholder="请输入拒绝原因" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="rejectDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="reject">确认拒绝</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'AdminTitleApplication',
  setup() {
    const applications = ref([])
    const rejectDialogVisible = ref(false)
    const rejectForm = ref({ applicationId: '', reason: '' })
    const fetchApplications = async () => {
      const res = await axios.get('/api/admin/titles', { params: { page: 1, size: 50 } })
      applications.value = res.data || []
    }
    let timer = null
    onMounted(() => {
      fetchApplications()
      // 定时轮询刷新
      timer = setInterval(() => {
        fetchApplications()
      }, 5000)
    })
    onUnmounted(() => {
      if (timer) clearInterval(timer)
    })
    const approve = async (id) => {
      const res = await axios.put(`/api/admin/titles/${id}/approve`)
      if (res.data && res.data.includes('通过')) {
        ElMessage.success('审批通过')
        fetchApplications()
        
        // 触发待办事项检查
        try {
          await axios.get('/api/admin/todo')
          window.dispatchEvent(new CustomEvent('check-admin-todos'))
        } catch (error) {
          console.error('更新待办事项状态失败:', error)
        }
      } else {
        ElMessage.error(res.data || '操作失败')
      }
    }
    const showRejectDialog = (id) => {
      rejectForm.value.applicationId = id
      rejectForm.value.reason = ''
      rejectDialogVisible.value = true
    }
    const reject = async () => {
      if (!rejectForm.value.reason) {
        ElMessage.error('请填写拒绝原因')
        return
      }
      const res = await axios.put(`/api/admin/titles/${rejectForm.value.applicationId}/reject`, rejectForm.value.reason, { headers: { 'Content-Type': 'application/json' } })
      if (res.data && res.data.includes('拒绝')) {
        ElMessage.success('已拒绝')
        rejectDialogVisible.value = false
        fetchApplications()
        
        // 触发待办事项检查
        try {
          await axios.get('/api/admin/todo')
          window.dispatchEvent(new CustomEvent('check-admin-todos'))
        } catch (error) {
          console.error('更新待办事项状态失败:', error)
        }
      } else {
        ElMessage.error(res.data || '操作失败')
      }
    }
    const getStatusType = (status) => {
      if (status === '审批中') return 'info'
      if (status === '已通过') return 'success'
      if (status === '未通过') return 'danger'
      return ''
    }
    const getAttachmentUrl = (url) => {
      if (!url) return ''
      // 从/uploads/xxx格式中提取文件名
      let fileName = url
      if (url.startsWith('/uploads/')) {
        fileName = url.substring(9) // 去掉'/uploads/'前缀
      }
      // 使用下载接口
      return `/api/title-attachment/${fileName}`
    }
    return {
      applications,
      fetchApplications,
      approve,
      showRejectDialog,
      rejectDialogVisible,
      rejectForm,
      reject,
      getStatusType,
      getAttachmentUrl
    }
  }
}
</script>

<style scoped>
.admin-title-application {
  max-width: 1000px;
  margin: 0 auto;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style> 